package com.cy.pj.sys.controller;

import com.alibaba.fastjson.JSON;
import com.cy.pj.common.exception.ServiceException;
import com.github.pagehelper.util.StringUtil;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/file")
public class FileController {

    public void checkImage(MultipartFile picture){
        //验证图片是否是图片文件
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(picture.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("当前文件不是图片文件，无法转化图片存储");
        }
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if(width == 0 || height ==0){
            throw new ServiceException("请上传类型为jpg,png等类型的图片文件");
        }
        //解析名称
        String picName = picture.getOriginalFilename();
        if (StringUtil.isEmpty(picName)) {
            throw new ServiceException( "文件不存在");
        }
        int index = picName.lastIndexOf(".");
        if (index == -1) {
            throw new ServiceException("图片后缀缺失");
        }
        String suffix = picName.substring(index).toLowerCase();
        if (!suffix.matches(".(png|jpg|jpeg|gif|img)")) {
            throw new ServiceException("图片后缀不规范,或非图片文件");
        }

        //判断文件是否存在
        if (picture == null) {
            throw new ServiceException("文件不存在");
        }
    }

    /**
     * 富文本上传 与普通不同
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(value = "uploadFwb")
    public Map<String, Object> imgUpDownFwb(@RequestParam("file") MultipartFile file) throws IOException {

        //图片验证
        checkImage(file);

        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        fileName = UUID.randomUUID()+suffixName;

        String path = ResourceUtils.getURL("classpath:").getPath()+"public/img/";
        file.transferTo(new File(path+fileName));
        Map<String,Object> result = new HashMap<>();
        result.put("state", "SUCCESS");//image.jwd.cn nginx反向代理,也正是因为这个路径所以无需配置config.json里面的路径
        result.put("url",   "/img/"+fileName);//图片回显
        result.put("original", "");
        result.put("type", suffixName);
        result.put("size", file.getSize());
        result.put("title", fileName);
        return result;
    }

    /**
     * ueditor文件上传方法
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/uploadfile",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam(value= "file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Date date = new Date();
        String path = null;
        try {
            path = ResourceUtils.getURL("classpath:").getPath()+"public/file/";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //附件后缀
        String last = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());

        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid+last;

        File fileT = new File(path,fileName);
        if(!fileT.exists()){
            fileT.mkdirs();
        }
        Map<String, Object> result = new HashMap<String,Object>();
        try {
            file.transferTo(fileT);
        } catch (IllegalStateException e) {
        } catch (IOException e1) {
        }
        result.put("state", "SUCCESS");
        result.put("url","/file/"+fileName);
        result.put("original", "");
        result.put("type", last);
        result.put("size", file.getSize());
        result.put("title", fileName);
        return result;
    }


    @PostMapping(value = "upload")
    public String imgUpDown(@RequestParam("file") MultipartFile file) throws IOException {

        //图片验证
        checkImage(file);

        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        fileName = UUID.randomUUID()+suffixName;

        String path = ResourceUtils.getURL("classpath:").getPath()+"public/img/";
        file.transferTo(new File(path+fileName));

        return "/img/"+fileName;
    }

    @PostMapping(value = "uploads")
    public String imgUpDowns(@RequestParam("files") MultipartFile[] files) throws IOException {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            String url = imgUpDown(files[i]);
            list.add(url);
        }
        return JSON.toJSONString(list);
    }
}
